package com.WISSC.controller;


import com.WISSC.bean.IndividualEvent;
import com.WISSC.bean.Team;
import com.WISSC.bean.layuiBean.ResultPage;
import com.WISSC.bean.layuiBean.VoPage;
import com.WISSC.commen.BaseController;
import com.WISSC.service.*;
import com.WISSC.util.Respons.ResponseUtil;
import com.WISSC.util.date.DateUtil;
import com.WISSC.util.file.DownLoadFileUtils;
import com.WISSC.util.file.FilePath;
import com.WISSC.util.file.Picture;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static java.lang.System.out;

/**
 * <p>
 * 赛事个人信息表 前端控制器
 * </p>
 *
 * @author 张凯
 * @since 2019-05-06
 */
@Controller
@RequestMapping("/individualEvent")
@Api(value = "个人赛事积分 controller", tags = "个人赛事积分")
public class IndividualEventController extends BaseController {


    @Autowired
    IndividualEventService individualEventService;
    @Autowired
    ExperienceUserService experienceUserService;
    @Autowired
    OccupationService occupationService;
    @Autowired
    StudentService studentService;
    @Autowired
    ConfigureService configureService;

    //首页
    @RequestMapping(value = "main.html", method = RequestMethod.GET)
    public String main() {
        return "main/individual";
    }

    //跳转添加页面
    @RequestMapping(value = "individual_add.html", method = RequestMethod.GET)
    public String individual_add() {
        return "add/individual_add";
    }

    //跳转编辑页面
    @RequestMapping(value = "individual_edit.html", method = RequestMethod.GET)
    public String individual_edit(Model model, String url, Long id) {
        model.addAttribute("url", url);
        model.addAttribute("id", id);
        return "edit/individual_edit";
    }

    @RequestMapping(value = "userIndex.html", method = RequestMethod.GET)
    public String userIndex() {
        return "userIndex";
    }

    @RequestMapping(value = "userLogin.html", method = RequestMethod.GET)
    public String userLogin() {
        return "userLogin";
    }

    //跳转个人赛事页面
    @RequestMapping(value = "selectById.html", method = RequestMethod.GET)
    public String selectById() {
        return "individualEvent_select";
    }

    //个人信息查询登陆页面
    @RequestMapping(value = "individualEvent_login.html", method = RequestMethod.GET)
    public String individualEvent_login() {
        return "individualEvent_login";
    }

    //个人信息查询首页
    @RequestMapping(value = "individualEvent_index.html", method = RequestMethod.GET)
    public String individualEvent_index(Model model, String name, String idNumber, String city, Long id) {
        model.addAttribute("name", name);
        model.addAttribute("idNumber", idNumber);
        model.addAttribute("city", city);
        model.addAttribute("id", id);
        model.addAttribute("url", configureService.getById(1).getConfigure());
        return "individualEvent_index";
    }

    //跳转个人信息
    @RequestMapping(value = "individualEvent_select.html", method = RequestMethod.GET)
    public String individualEvent_select(Model model, String name, String idNumber, String city, Long id) {
        out.println("name:" + name);
        out.println("idNumber:" + idNumber);
        model.addAttribute("name", name);
        model.addAttribute("idNumber", idNumber);
        IndividualEvent individualEvent = individualEventService.getById(id);
        IndividualEvent individualEvent1 = individualEventService.select(idNumber);
        if (individualEvent == null) {
            return "individual/individualEvent_select";
        } else {
            String time = DateUtil.numberDateFormat(individualEvent.getBirth() + "", "yyyy-MM-dd");
            model.addAttribute("data", time);
            model.addAttribute("model", individualEvent1);
            List<IndividualEvent> list = individualEventService.country(city, idNumber);
            for (int i = 0; i < list.size(); i++) {
                if (i == 0) {
                    if (individualEvent1.getNationalRanking() == 2) {
                        model.addAttribute("county", "暂无参加排名");
                    } else {
                        model.addAttribute("county", list.get(i).getRow());
                    }

                }
                if (i == 1) {
                    if (individualEvent1.getProvinceRanking() == 2) {
                        model.addAttribute("county1", "暂无参加排名");
                    } else {
                        model.addAttribute("county1", list.get(i).getRow());
                    }

                }
                if (i == 2) {
                    if (individualEvent1.getCityRanking() == 2) {
                        model.addAttribute("county2", "暂无参加排名");
                    } else {
                        model.addAttribute("county2", list.get(i).getRow());
                    }
                }
            }
            model.addAttribute("occ", occupationService.list(idNumber));
            model.addAttribute("student", studentService.certificate(idNumber));
            out.println("model:" + model);
            return "individual/individualEvent_select";
        }

    }

    /**
     * @param param1
     * @param param2
     * @return 个人信息添加
     */
    @RequestMapping(value = "individualEventInsert", method = RequestMethod.POST)
    @ResponseBody
    public String individualEventInsert(String param1, String param2, HttpSession session) {
        IndividualEvent individualEvent = JSONObject.parseObject(param1, IndividualEvent.class);
        if (getUser(session).getStatus() == 2) {
            individualEvent.setType(1);
            individualEvent.setFlag(4);
        } else {
            individualEvent.setType(2);
            individualEvent.setFlag(1);
        }
        return individualEventService.individualEventInsert(param2, individualEvent);
    }

    /**
     * @param page
     * @param limit
     * @param name
     * @param idNumber
     * @param combat
     * @param raceAge
     * @param city
     * @return 查询 + 分页
     */
    @RequestMapping(value = "selectMyPage", method = RequestMethod.GET)
    @ResponseBody
    public ResultPage<IndividualEvent> selectMyPage(

            @ApiParam(name = "page", value = "页码", required = true)
            @RequestParam int page,
            @ApiParam(name = "limit", value = "查询条数", required = true)
            @RequestParam int limit,
            String name,
            Integer idNumber,
            Long birth,
            String combat,
            Integer raceAge,
            String city, HttpSession session) {
        boolean admin = false;
        if (getUser(session).getRoles().getRoleValue().equals("9f77d5a8-75c6-4d06-adf9-a37e727d491a")) {
            admin = true;
        }

        return individualEventService.selectMyPage(page, limit, name, idNumber, birth, combat, raceAge, city, session, admin);
    }

    /**
     * @param individualEvent
     * @return 个人信息删除
     */
    @RequestMapping(value = "remove", method = RequestMethod.POST)
    @ResponseBody
    public Map remove(@RequestBody IndividualEvent individualEvent, HttpSession session) {
        IndividualEvent i = individualEventService.getById(individualEvent.getId());
        File  file = new File(i.getUrl());
        if (file.isFile() && file.exists()) {
            file.delete();
        }
        if (getUser(session).getStatus() == 2) {
            if (individualEventService.removeById(individualEvent)) {
                if (experienceUserService.removeByIndividualEventId(individualEvent.getId())) {
                    return ResponseUtil.getSuccessMap();
                }
            }
        } else {
            individualEvent.setType(2);
            individualEvent.setFlag(2);
            individualEventService.updateById(individualEvent);
            return ResponseUtil.getSuccessMap();
        }
        return ResponseUtil.getExceptionMap();
    }

    /**
     * @return 个人信息修改
     */
    @RequestMapping(value = "updateById", method = RequestMethod.POST)
    @ResponseBody
    public Map update(String param1, String param2, HttpSession session) {
        IndividualEvent individualEvent = JSONObject.parseObject(param1, IndividualEvent.class);
        if (getUser(session).getStatus() == 2) {
            individualEvent.setType(1);
            individualEvent.setFlag(4);
            return individualEventService.updateindividualEvent(individualEvent, param2);
        } else {
            IndividualEvent i = new IndividualEvent();
            i.setName(individualEvent.getName());
            i.setSex(individualEvent.getSex());
            i.setIdNumber(individualEvent.getIdNumber());
            i.setBirth(individualEvent.getBirth());
            i.setCity(individualEvent.getCity());
            i.setCombat(individualEvent.getCombat());
            i.setRaceAge(individualEvent.getRaceAge());
            i.setCityRanking(individualEvent.getCityRanking());
            i.setProvinceRanking(individualEvent.getProvinceRanking());
            i.setNationalRanking(individualEvent.getNationalRanking());
            i.setBeforeId(individualEvent.getId());
            i.setUrl(individualEvent.getUrl());
            i.setFlag(3);
            i.setType(2);
            String[] split = param2.split("-");
            List list = new ArrayList();
            for (int j = 0; j < split.length; j++) {
                list.add(split[j]);
            }
            String param3 = "";
            for (int j = 0; j < list.size(); j++) {
                String arr = (String) list.get(j);
                String[] str = arr.split(",");
                param3 += str[1] + "," + str[2] + "," + str[3] + "," + str[4] + "-";
            }
            individualEventService.individualEventInsert(param3, i);
            return ResponseUtil.getSuccessMap();
        }
    }

    /**
     * @param
     * @return 个人赛事积分查询 通过idNumber查询  结果返回ResultPage
     */
    /* @RequestMapping(value = "selectByidNumber", method = RequestMethod.GET)
    @ResponseBody
    public ResultPage<IndividualEvent> selectByidNumber(String idNumber) {
        List list = new ArrayList();
        list = individualEventService.selectByidNumber(idNumber);
        ResultPage rp= new ResultPage();
        rp.setCount(list.size());
        System.out.println(list.size());
        rp.setCode(0);
        rp.setMsg(":");
        rp.setData(list);
        return rp;
    }*/

    /* *//**
     * @param session
     * @return 个人赛事积分查询 通过idNumber查询 结果返回list集合
     *//*
    @RequestMapping(value = "select", method = RequestMethod.GET)
    @ResponseBody
    public List<IndividualEvent> select(HttpSession session) {

        return individualEventService.selectByidNumber(session);
    }*/


    /**
     * @param individualEvent
     * @return 个人信息登陆
     */
    @RequestMapping(value = "land", method = RequestMethod.POST)
    @ResponseBody
    public boolean login(IndividualEvent individualEvent, HttpSession session1) {
        if (individualEventService.login(individualEvent, session1)) {
            return true;
        }
        return false;
    }

    //获取个人信息图片
    @RequestMapping("/getPhoto")
    public void getPhoto(HttpServletResponse response, @RequestParam("path") String path) throws Exception {
        out.println("path= " + path);
        File file = new File(path);
        FileInputStream fis;
        fis = new FileInputStream(file);
        long size = file.length();
        byte[] temp = new byte[(int) size];
        fis.read(temp, 0, (int) size);
        fis.close();
        byte[] data = temp;
        response.setContentType("image/png");
        OutputStream out = response.getOutputStream();
        out.write(data);
        out.flush();
        out.close();
    }


    @RequestMapping(value = "selectMyPageIndividualEvent", method = RequestMethod.GET)
    @ResponseBody
    public ResultPage<IndividualEvent> selectMyPageTeam(VoPage voPage, HttpSession session) {

        out.println("12");
        return individualEventService.selectMyPage(session, voPage);
    }

    /**
     * @param session
     * @param idNumber
     * @return 获取图片
     */
    @RequestMapping(value = "selectByIdNumber", method = RequestMethod.GET)
    @ResponseBody
    public List<IndividualEvent> selectByIdNumber(HttpSession session, String idNumber) {
        return individualEventService.selectByIdNumber(idNumber);
    }

    //批量删除
    @RequestMapping(value = "deleteBtId", method = RequestMethod.POST)
    @ResponseBody
    public Map deleteById(String ids, HttpSession sessions) {
        String[] a = ids.split(",");
        for (int i = 1; i < a.length; i++) {
            IndividualEvent individualEvent = individualEventService.getById(a[i]);
            File  file = new File(individualEvent.getUrl());
            if (file.isFile() && file.exists()) {
                file.delete();
            }
        }
        if (getUser(sessions).getStatus() == 2) {
            for (int i = 1; i < a.length; i++) {
                individualEventService.removeById(a[i]);
                IndividualEvent individualEvent = new IndividualEvent();
                individualEvent.setId(Long.parseLong(a[i]));
                experienceUserService.removeByIndividualEventId(individualEvent.getId());
            }
            return ResponseUtil.getSuccessMap();
        } else {
            for (int i = 1; i < a.length; i++) {
                IndividualEvent individualEvent = new IndividualEvent();
                individualEvent.setId(Long.parseLong(a[i]));
                individualEvent.setType(2);
                individualEvent.setFlag(2);
                individualEventService.updateById(individualEvent);
            }
            return ResponseUtil.getSuccessMap();

        }
    }

    /**
     * @param id
     * @return 回显所在地区
     */
    @RequestMapping(value = "getTeamCity", method = RequestMethod.POST)
    @ResponseBody
    public Map getTeamCity(Long id) {
        return individualEventService.getTeamCity(id);
    }


    /**
     * @param voPage
     * @param name
     * @param idNumber
     * @return 新赛事查询
     */
    @RequestMapping(value = "listIndividualEvent", method = RequestMethod.GET)
    @ResponseBody
    public ResultPage<IndividualEvent> listIndividualEvent(VoPage voPage, String name, String idNumber) {

        return individualEventService.listIndividualEvent(voPage, name, idNumber);
    }

    //生成海报
    @RequestMapping(value = "/getPoster", method = RequestMethod.GET)
    @ResponseBody
    public void getPoster(String sum, String idNumber, HttpServletResponse response) throws Exception {
        List<IndividualEvent> list = individualEventService.getIndividualEvent(idNumber);
        String str = "";
        for (int i = 0; i < list.size(); i++) {
            String res = "";
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            res = simpleDateFormat.format(list.get(i).getMatchTime());
            str += "赛事日期：" + res + " 赛事名称：" + list.get(i).getMatchName() + " 赛事名次：" + list.get(i).getRanking() + " 赛事积分：" + list.get(i).getRaceAge() + "=";
        }
        String body = sum + "=" + str;
        String url = FilePath.getPath("person");
        String[] split = url.split("/");
        String aa = "";
        String bb = url + ".jpg";
        for (int i = 0; i < split.length; i++) {
            if (i == split.length - 1) {
                aa = split[i]+".jpg";
            }
        }
        new Picture().createImage(body, new Font("黑体", Font.BOLD, 18), new File(url + ".jpg"));
        DownLoadFileUtils.downloadFile(response, bb, aa);

    }

    //通过
    @RequestMapping(value = "adopt", method = RequestMethod.POST)
    @ResponseBody
    public Map abopt(@RequestBody IndividualEvent individualEvent) {
        IndividualEvent i = individualEventService.getById(individualEvent);
        if (i.getFlag() == 2) {
            if (individualEventService.removeById(individualEvent) && experienceUserService.removeByIndividualEventId(i.getId())) {
                return ResponseUtil.getSuccessMap();
            }
        } else if (i.getFlag() == 1) {
            individualEvent.setType(1);
            individualEvent.setFlag(4);
            if (individualEventService.updateById(individualEvent)) {
                return ResponseUtil.getSuccessMap();
            }
        } else {
            individualEvent.setType(1);
            individualEvent.setFlag(4);
            individualEventService.updateById(individualEvent);
            if (individualEventService.removeById(i.getBeforeId()) && experienceUserService.removeByIndividualEventId(i.getBeforeId())) {
                return ResponseUtil.getSuccessMap();
            }
        }
        return ResponseUtil.getExceptionMap();
    }

    //不通过
    @RequestMapping(value = "noAdopt", method = RequestMethod.POST)
    @ResponseBody
    public Map noAdopt(@RequestBody IndividualEvent individualEvent) {

        IndividualEvent i = individualEventService.getById(individualEvent);
        if (i.getFlag() == 2) {
            i.setFlag(4);
            i.setType(1);
            if (individualEventService.updateById(i)) {
                return ResponseUtil.getSuccessMap();
            }

        } else if (i.getFlag() == 1) {
            if (individualEventService.removeById(individualEvent) && experienceUserService.removeByIndividualEventId(individualEvent.getId())) {
                return ResponseUtil.getSuccessMap();
            }
        } else {
            if (individualEventService.removeById(individualEvent) && experienceUserService.removeByIndividualEventId(individualEvent.getId())) {
                return ResponseUtil.getSuccessMap();
            }
        }

        return ResponseUtil.getExceptionMap();
    }

}